<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>动画效果</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    canvas {
      display: block;
      background-color: #000;
    }
  </style>
</head>

<body>
  <canvas id="canvas"></canvas>

  <script>
    const canvas = document.querySelector('#canvas')
    // 根据浏览器的视窗 自动设置全屏动画
    canvas.width = window.visualViewport.width
    canvas.height = window.visualViewport.height

    // 获取绘制环境
    const ctx = canvas.getContext('2d')

    let [x, y, vx] = [100, 100, 2]

    // 让矩形方块向右移动起来
    function moveRight() {

      // 清除之前绘制的图片
      ctx.clearRect(0, 0, canvas.width, canvas.height)

      // 渲染模块
      ctx.beginPath()
      ctx.fillStyle = 'orange'
      ctx.fillRect(x, y, 100, 100)

      if (x < 100 || x > 1800) vx *= -1 // 反复横跳

      // 数据更新模块
      x += vx

      requestAnimationFrame(moveRight)


    }

    moveRight()
  </script>
</body>

</html>